'use client';

import React, { useState } from 'react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Badge from '@/components/ui/Badge';
import { 
  Plus,
  Settings,
  Play,
  Network,
  Cloud,
  Server,
  Users,
  Database,
  Brain,
  GitBranch,
  ArrowRight,
  Monitor,
  Cpu,
  HardDrive
} from 'lucide-react';

interface Node {
  id: string;
  name: string;
  type: 'cloud' | 'edge';
  location: string;
  status: 'active' | 'inactive' | 'maintenance';
  resources: {
    cpu: string;
    memory: string;
    gpu: string;
    network: string;
  };
  connectedNodes: string[];
}

interface EvolutionChain {
  id: string;
  name: string;
  type: 'knowledge' | 'sample' | 'model';
  status: 'active' | 'inactive';
  cloudNodes: string[];
  edgeNodes: string[];
  description: string;
  createdAt: string;
  lastUpdated: string;
  performance: {
    throughput: string;
    latency: string;
    efficiency: number;
  };
}

export default function DistributedPage() {
  const [activeTab, setActiveTab] = useState<'overview' | 'chains' | 'nodes'>('overview');
  
  const [nodes] = useState<Node[]>([
    {
      id: 'cloud_1',
      name: '北京数据中心',
      type: 'cloud',
      location: '北京市朝阳区',
      status: 'active',
      resources: {
        cpu: '64核心',
        memory: '512GB',
        gpu: '8×A100',
        network: '10Gbps'
      },
      connectedNodes: ['edge_1', 'edge_2', 'edge_3']
    },
    {
      id: 'edge_1',
      name: '变电站A边缘节点',
      type: 'edge',
      location: '北京市海淀区变电站A',
      status: 'active',
      resources: {
        cpu: '16核心',
        memory: '64GB',
        gpu: '2×RTX4090',
        network: '1Gbps'
      },
      connectedNodes: ['cloud_1']
    },
    {
      id: 'edge_2',
      name: '变电站B边缘节点',
      type: 'edge',
      location: '北京市昌平区变电站B',
      status: 'active',
      resources: {
        cpu: '16核心',
        memory: '64GB',
        gpu: '2×RTX4090',
        network: '1Gbps'
      },
      connectedNodes: ['cloud_1']
    },
    {
      id: 'edge_3',
      name: '变电站C边缘节点',
      type: 'edge',
      location: '北京市房山区变电站C',
      status: 'maintenance',
      resources: {
        cpu: '16核心',
        memory: '64GB',
        gpu: '2×RTX4090',
        network: '1Gbps'
      },
      connectedNodes: ['cloud_1']
    }
  ]);

  const [evolutionChains] = useState<EvolutionChain[]>([
    {
      id: '1',
      name: '默认知识进化链路（一云2边）',
      type: 'knowledge',
      status: 'active',
      cloudNodes: ['cloud_1'],
      edgeNodes: ['edge_1', 'edge_2'],
      description: '知识蒸馏和迁移学习协同进化配置',
      createdAt: '2024-11-15',
      lastUpdated: '2024-12-03',
      performance: {
        throughput: '150样本/秒',
        latency: '12ms',
        efficiency: 94.2
      }
    },
    {
      id: '2',
      name: '样本协同进化链路',
      type: 'sample',
      status: 'active',
      cloudNodes: ['cloud_1'],
      edgeNodes: ['edge_1', 'edge_2'],
      description: '分布式样本处理和数据增强配置',
      createdAt: '2024-11-20',
      lastUpdated: '2024-12-02',
      performance: {
        throughput: '200样本/秒',
        latency: '8ms',
        efficiency: 91.8
      }
    },
    {
      id: '3',
      name: '模型参数协同链路',
      type: 'model',
      status: 'inactive',
      cloudNodes: ['cloud_1'],
      edgeNodes: ['edge_1', 'edge_2', 'edge_3'],
      description: '分布式模型学习和参数同步协同进化配置',
      createdAt: '2024-11-25',
      lastUpdated: '2024-11-30',
      performance: {
        throughput: '80模型/小时',
        latency: '120ms',
        efficiency: 89.5
      }
    }
  ]);

  const getNodeStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge variant="success">在线</Badge>;
      case 'inactive':
        return <Badge variant="error">离线</Badge>;
      case 'maintenance':
        return <Badge variant="warning">维护中</Badge>;
      default:
        return <Badge variant="default">{status}</Badge>;
    }
  };

  const getChainStatusBadge = (status: string) => {
    switch (status) {
      case 'active':
        return <Badge variant="success">运行中</Badge>;
      case 'inactive':
        return <Badge variant="default">未激活</Badge>;
      default:
        return <Badge variant="default">{status}</Badge>;
    }
  };

  const getChainTypeIcon = (type: string) => {
    switch (type) {
      case 'knowledge':
        return <Brain className="h-5 w-5 text-purple-500" />;
      case 'sample':
        return <Database className="h-5 w-5 text-blue-500" />;
      case 'model':
        return <GitBranch className="h-5 w-5 text-green-500" />;
      default:
        return <Network className="h-5 w-5 text-gray-500" />;
    }
  };

  const getNodeTypeIcon = (type: string) => {
    return type === 'cloud' ? 
      <Cloud className="h-5 w-5 text-blue-500" /> : 
      <Server className="h-5 w-5 text-green-500" />;
  };

  const renderOverviewTab = () => (
    <div className="space-y-6">
      {/* 系统架构图 */}
      <Card className="p-6">
        <h3 className="text-xl font-semibold text-gray-900 mb-6">分布式协同进化架构</h3>
        <div className="flex items-center justify-center">
          <div className="flex flex-col items-center space-y-8">
            {/* 云端节点 */}
            <div className="flex items-center justify-center">
              <div className="bg-blue-50 p-6 rounded-lg border-2 border-blue-200">
                <div className="flex items-center space-x-4">
                  <Cloud className="h-8 w-8 text-blue-600" />
                  <div>
                    <h4 className="font-semibold text-gray-900">云端中心节点</h4>
                    <p className="text-sm text-gray-600">负责全局协调和知识整合</p>
                  </div>
                </div>
              </div>
            </div>

            {/* 连接线 */}
            <div className="flex items-center space-x-8">
              <div className="w-px h-16 bg-gray-300"></div>
              <ArrowRight className="h-6 w-6 text-gray-400 rotate-90" />
              <div className="w-px h-16 bg-gray-300"></div>
            </div>

            {/* 边缘节点 */}
            <div className="flex items-center space-x-8">
              {nodes.filter(node => node.type === 'edge').map((node, index) => (
                <div key={node.id} className="flex flex-col items-center">
                  <div className="bg-green-50 p-4 rounded-lg border-2 border-green-200">
                    <div className="flex items-center space-x-3">
                      <Server className="h-6 w-6 text-green-600" />
                      <div>
                        <h4 className="font-medium text-gray-900">{node.name}</h4>
                        <p className="text-xs text-gray-600">{node.location}</p>
                      </div>
                    </div>
                  </div>
                  {index < nodes.filter(node => node.type === 'edge').length - 1 && (
                    <ArrowRight className="h-4 w-4 text-gray-400 mt-4" />
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      </Card>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Cloud className="h-6 w-6 text-blue-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">云端节点</p>
              <p className="text-2xl font-bold text-gray-900">
                {nodes.filter(n => n.type === 'cloud').length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-2 bg-green-100 rounded-lg">
              <Server className="h-6 w-6 text-green-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">边缘节点</p>
              <p className="text-2xl font-bold text-gray-900">
                {nodes.filter(n => n.type === 'edge').length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-2 bg-purple-100 rounded-lg">
              <Network className="h-6 w-6 text-purple-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">进化链路</p>
              <p className="text-2xl font-bold text-gray-900">{evolutionChains.length}</p>
            </div>
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center">
            <div className="p-2 bg-yellow-100 rounded-lg">
              <Monitor className="h-6 w-6 text-yellow-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">平均效率</p>
              <p className="text-2xl font-bold text-gray-900">
                {(evolutionChains.reduce((sum, chain) => sum + chain.performance.efficiency, 0) / evolutionChains.length).toFixed(1)}%
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* 活跃链路状态 */}
      <Card className="p-6">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">活跃进化链路</h3>
        <div className="space-y-4">
          {evolutionChains.filter(chain => chain.status === 'active').map((chain) => (
            <div key={chain.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
              <div className="flex items-center space-x-4">
                {getChainTypeIcon(chain.type)}
                <div>
                  <h4 className="font-medium text-gray-900">{chain.name}</h4>
                  <p className="text-sm text-gray-600">{chain.description}</p>
                </div>
              </div>
              <div className="flex items-center space-x-4">
                <div className="text-right">
                  <p className="text-sm font-medium text-gray-900">{chain.performance.efficiency}%</p>
                  <p className="text-xs text-gray-600">效率</p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-medium text-gray-900">{chain.performance.throughput}</p>
                  <p className="text-xs text-gray-600">吞吐量</p>
                </div>
                {getChainStatusBadge(chain.status)}
              </div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );

  const renderChainsTab = () => (
    <div className="space-y-6">
      {/* 链路管理操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-xl font-semibold text-gray-900">进化链路配置</h3>
          <p className="text-gray-600 mt-1">管理知识、样本、模型三类协同进化链路</p>
        </div>
        <Button variant="primary">
          <Plus className="h-4 w-4 mr-2" />
          创建新链路
        </Button>
      </div>

      {/* 链路类型筛选 */}
      <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg">
        <button className="flex-1 py-2 px-4 rounded-md text-sm font-medium bg-white text-blue-600 shadow-sm">
          <Brain className="h-4 w-4 inline mr-2" />
          知识协同
        </button>
        <button className="flex-1 py-2 px-4 rounded-md text-sm font-medium text-gray-600 hover:text-gray-900">
          <Database className="h-4 w-4 inline mr-2" />
          样本协同
        </button>
        <button className="flex-1 py-2 px-4 rounded-md text-sm font-medium text-gray-600 hover:text-gray-900">
          <GitBranch className="h-4 w-4 inline mr-2" />
          模型协同
        </button>
      </div>

      {/* 链路列表 */}
      <div className="space-y-4">
        {evolutionChains.map((chain) => (
          <Card key={chain.id} className="p-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                {getChainTypeIcon(chain.type)}
                <div>
                  <div className="flex items-center space-x-3">
                    <h4 className="text-lg font-semibold text-gray-900">{chain.name}</h4>
                    {getChainStatusBadge(chain.status)}
                  </div>
                  <p className="text-gray-600 mt-1">{chain.description}</p>
                  <div className="flex items-center space-x-4 mt-2 text-sm text-gray-500">
                    <span>创建时间: {chain.createdAt}</span>
                    <span>更新时间: {chain.lastUpdated}</span>
                  </div>
                </div>
              </div>
              <div className="flex items-center space-x-3">
                <Button size="sm" variant="secondary">
                  <Settings className="h-4 w-4 mr-1" />
                  配置
                </Button>
                <Button size="sm" variant={chain.status === 'active' ? 'warning' : 'primary'}>
                  <Play className="h-4 w-4 mr-1" />
                  {chain.status === 'active' ? '停止' : '启动'}
                </Button>
              </div>
            </div>

            {/* 节点配置 */}
            <div className="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div>
                <h5 className="font-medium text-gray-900 mb-3">云端节点</h5>
                <div className="space-y-2">
                  {chain.cloudNodes.map((nodeId) => {
                    const node = nodes.find(n => n.id === nodeId);
                    return node ? (
                      <div key={nodeId} className="flex items-center justify-between p-3 bg-blue-50 rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Cloud className="h-4 w-4 text-blue-500" />
                          <span className="font-medium text-gray-900">{node.name}</span>
                        </div>
                        {getNodeStatusBadge(node.status)}
                      </div>
                    ) : null;
                  })}
                </div>
              </div>

              <div>
                <h5 className="font-medium text-gray-900 mb-3">边缘节点</h5>
                <div className="space-y-2">
                  {chain.edgeNodes.map((nodeId) => {
                    const node = nodes.find(n => n.id === nodeId);
                    return node ? (
                      <div key={nodeId} className="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                        <div className="flex items-center space-x-3">
                          <Server className="h-4 w-4 text-green-500" />
                          <span className="font-medium text-gray-900">{node.name}</span>
                        </div>
                        {getNodeStatusBadge(node.status)}
                      </div>
                    ) : null;
                  })}
                </div>
              </div>
            </div>

            {/* 性能指标 */}
            <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-gray-50 p-4 rounded-lg">
                <span className="text-sm text-gray-600">吞吐量</span>
                <p className="text-xl font-bold text-gray-900 mt-1">{chain.performance.throughput}</p>
              </div>
              <div className="bg-gray-50 p-4 rounded-lg">
                <span className="text-sm text-gray-600">延迟</span>
                <p className="text-xl font-bold text-gray-900 mt-1">{chain.performance.latency}</p>
              </div>
              <div className="bg-gray-50 p-4 rounded-lg">
                <span className="text-sm text-gray-600">效率</span>
                <p className="text-xl font-bold text-gray-900 mt-1">{chain.performance.efficiency}%</p>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );

  const renderNodesTab = () => (
    <div className="space-y-6">
      {/* 节点管理操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-xl font-semibold text-gray-900">节点管理</h3>
          <p className="text-gray-600 mt-1">管理云端和边缘计算节点</p>
        </div>
        <Button variant="primary">
          <Plus className="h-4 w-4 mr-2" />
          添加节点
        </Button>
      </div>

      {/* 节点列表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {nodes.map((node) => (
          <Card key={node.id} className="p-6">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-3">
                {getNodeTypeIcon(node.type)}
                <div>
                  <h4 className="text-lg font-semibold text-gray-900">{node.name}</h4>
                  <p className="text-gray-600">{node.location}</p>
                </div>
              </div>
              {getNodeStatusBadge(node.status)}
            </div>

            {/* 资源信息 */}
            <div className="space-y-3 mb-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Cpu className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-600">CPU</span>
                </div>
                <span className="text-sm font-medium text-gray-900">{node.resources.cpu}</span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <HardDrive className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-600">内存</span>
                </div>
                <span className="text-sm font-medium text-gray-900">{node.resources.memory}</span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Monitor className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-600">GPU</span>
                </div>
                <span className="text-sm font-medium text-gray-900">{node.resources.gpu}</span>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <Network className="h-4 w-4 text-gray-500" />
                  <span className="text-sm text-gray-600">网络</span>
                </div>
                <span className="text-sm font-medium text-gray-900">{node.resources.network}</span>
              </div>
            </div>

            {/* 连接的节点 */}
            <div className="mb-4">
              <h5 className="text-sm font-medium text-gray-900 mb-2">连接节点</h5>
              <div className="flex flex-wrap gap-2">
                {node.connectedNodes.map((connectedId) => {
                  const connectedNode = nodes.find(n => n.id === connectedId);
                  return connectedNode ? (
                    <Badge key={connectedId} variant="secondary">
                      {connectedNode.name}
                    </Badge>
                  ) : null;
                })}
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-2">
              <Button size="sm" variant="secondary" className="flex-1">
                <Settings className="h-4 w-4 mr-1" />
                配置
              </Button>
              <Button size="sm" variant="secondary" className="flex-1">
                <Monitor className="h-4 w-4 mr-1" />
                监控
              </Button>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">分布式协同进化机制</h1>
          <p className="text-sm text-gray-600 mt-0.5">电力云边模型分布式协同进化架构管理</p>
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" size="sm">
            <Monitor className="h-4 w-4 mr-2" />
            系统监控
          </Button>
          <Button variant="primary" size="sm">
            <Settings className="h-4 w-4 mr-2" />
            全局配置
          </Button>
        </div>
      </div>

      {/* 标签页导航 */}
      <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg">
        <button
          onClick={() => setActiveTab('overview')}
          className={`flex-1 py-2 px-4 rounded-md text-sm font-medium transition-colors ${
            activeTab === 'overview'
              ? 'bg-white text-blue-600 shadow-sm'
              : 'text-gray-600 hover:text-gray-900'
          }`}
        >
          <Network className="h-4 w-4 inline mr-2" />
          架构总览
        </button>
        <button
          onClick={() => setActiveTab('chains')}
          className={`flex-1 py-2 px-4 rounded-md text-sm font-medium transition-colors ${
            activeTab === 'chains'
              ? 'bg-white text-blue-600 shadow-sm'
              : 'text-gray-600 hover:text-gray-900'
          }`}
        >
          <GitBranch className="h-4 w-4 inline mr-2" />
          进化链路
        </button>
        <button
          onClick={() => setActiveTab('nodes')}
          className={`flex-1 py-2 px-4 rounded-md text-sm font-medium transition-colors ${
            activeTab === 'nodes'
              ? 'bg-white text-blue-600 shadow-sm'
              : 'text-gray-600 hover:text-gray-900'
          }`}
        >
          <Users className="h-4 w-4 inline mr-2" />
          节点管理
        </button>
      </div>

      {/* 标签页内容 */}
      {activeTab === 'overview' && renderOverviewTab()}
      {activeTab === 'chains' && renderChainsTab()}
      {activeTab === 'nodes' && renderNodesTab()}
    </div>
  );
} 